import json

from openai import OpenAI
import os
import time
from typing import Generator, Tuple


EVALUATION_PROMPT = """
请根据面试对话历史生成结构化评估：

【输入数据】
面试记录：
{history}

岗位要求：
{position}

【输出要求】
1. 按百分制给出五项评分
2. 每项提供50字评估依据
3. 输出JSON格式：
{{
  "technical_ability": {score},
  "learning_ability": {score},
  "team_collaboration": {score},
  "problem_solving": {score},
  "communication_expression": {score},
  "evaluation_details": [
    {{"dimension": "...", "score": ..., "reason": "..."}},
    ...
  ]
}}
"""

system_prompt = """
你是一个专业严谨的AI面试官，需要完成以下任务：

【角色设定】
1. 面试流程分三个阶段：
   - 技术面试（6个问题）
   - 行为面试（3个问题）
   - 总结反馈（1个问题）
2. 基于以下信息生成问题：
   职位要求：{position_info}
   候选人简历：{resume_info}
3. 评分维度（百分制）：
   - 技术能力（权重40%）
   - 学习能力（权重20%）
   - 团队协作（权重15%）
   - 问题解决（权重15%）
   - 沟通表达（权重10%）

【对话规则】
1. 每次只问1个问题
2. 问题间保持逻辑连贯
3. 第10轮自动结束面试
4. 使用中文提问，保持专业但友好的语气

【输出格式要求】
{{"current_round": 当前轮次, "phase": 阶段名称}}
问题内容
"""

class DeepSeekInterviewer:
    def __init__(self):
        self.client = OpenAI(
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
        )
        self.system_prompt = """（在此粘贴之前设计的系统提示词）"""
        self.max_rounds = 10
        self.current_round = 0
        self.interview_phase = "technical"  # technical/behavioral/summary

    def _initialize_session(self, resume: str, position: str) -> list:
        """初始化对话上下文"""
        return [
            {
                "role": "system",
                "content": self.system_prompt.format(
                    position_info=position,
                    resume_info=resume
                )
            }
        ]

    def stream_chat(self, messages: list) -> Generator[Tuple[str, str], None, None]:
        """流式对话生成器"""
        full_reasoning = ""
        full_answer = ""
        is_reasoning = True

        try:
            stream = self.client.chat.completions.create(
                model="deepseek-r1",
                messages=messages,
                stream=True,
                temperature=0.7,
                max_tokens=500
            )

            for chunk in stream:
                if not chunk.choices:
                    continue

                delta = chunk.choices[0].delta

                # 处理推理过程
                if hasattr(delta, "reasoning_content") and delta.reasoning_content:
                    if is_reasoning:
                        full_reasoning += delta.reasoning_content
                        yield "reasoning", delta.reasoning_content

                # 处理正式回答
                if hasattr(delta, "content") and delta.content:
                    if is_reasoning:
                        is_reasoning = False
                        yield "phase", "\n答案："
                    full_answer += delta.content
                    yield "answer", delta.content

            # 更新对话轮次和阶段
            self._update_interview_state()

        except Exception as e:
            yield "error", f"API调用失败: {str(e)}"

    def _update_interview_state(self):
        """更新面试状态"""
        self.current_round += 1

        if self.current_round <= 6:
            self.interview_phase = "technical"
        elif self.current_round <= 9:
            self.interview_phase = "behavioral"
        else:
            self.interview_phase = "summary"

    def run_interview(self, resume: str, position: str):
        """运行完整面试流程"""
        messages = self._initialize_session(resume, position)

        while self.current_round < self.max_rounds:
            print(f"\n{'=' * 20} 第{self.current_round + 1}轮 [{self.interview_phase}] {'=' * 20}")

            # 生成AI提问
            full_response = ""
            for resp_type, content in self.stream_chat(messages):
                if resp_type == "reasoning":
                    print(f"[思考] {content}", end="", flush=True)
                elif resp_type == "phase":
                    print(content, end="", flush=True)
                elif resp_type == "answer":
                    print(content, end="", flush=True)
                    full_response += content
                elif resp_type == "error":
                    print(f"\n错误发生: {content}")
                    return

            # 记录AI提问
            messages.append({"role": "assistant", "content": full_response})

            # 获取用户回答
            user_input = input("\n\n你的回答：")
            messages.append({"role": "user", "content": user_input})

        # 面试结束后生成评估
        self.generate_evaluation(messages)

    def generate_evaluation(self, history: list):
        """生成最终评估"""
        print("\n\n正在生成评估报告...")
        evaluation_prompt = EVALUATION_PROMPT  # 使用之前设计的评估提示词

        try:
            response = self.client.chat.completions.create(
                model="deepseek-r1",
                messages=[{"role": "user", "content": evaluation_prompt}],
                temperature=0.2
            )

            evaluation = self._parse_evaluation(response.choices[0].message.content)
            self._display_evaluation(evaluation)

        except Exception as e:
            print(f"评估生成失败: {str(e)}")

    def _parse_evaluation(self, response: str) -> dict:
        """解析评估结果"""
        try:
            # 提取JSON部分
            start = response.find("{")
            end = response.rfind("}") + 1
            return json.loads(response[start:end])
        except:
            return {"error": "评估解析失败"}

    def _display_evaluation(self, evaluation: dict):
        """可视化展示评估结果"""
        print("\n" + "=" * 20 + " 最终评估 " + "=" * 20)
        if "error" in evaluation:
            print(evaluation["error"])
            return

        print(f"技术能力: {evaluation['technical_ability']}/100")
        print(f"学习能力: {evaluation['learning_ability']}/100")
        print(f"团队协作: {evaluation['team_collaboration']}/100")
        print(f"问题解决: {evaluation['problem_solving']}/100")
        print(f"沟通表达: {evaluation['communication_expression']}/100")
        print("\n详细分析：")
        for detail in evaluation.get("evaluation_details", []):
            print(f"- {detail['dimension']}: {detail['reason'][:50]}...")


if __name__ == "__main__":
    interviewer = DeepSeekInterviewer()

    # 模拟输入简历和职位信息
    sample_resume = """候选人简历内容..."""
    sample_position = """招聘职位要求..."""

    interviewer.run_interview(
        resume=sample_resume,
        position=sample_position
    )